<?php

namespace app\http;

use think\worker\Server;
use Workerman\Lib\Timer;

class Worker extends Server
{
    protected static $heartbeat_time = 55;

    public function init()
    {
        $this->worker->name = "gas-worker";
    }

    public function onConnect($connection)
    {
        echo("connect....\n");
    }

    public function reconnect($connection)
    {
        $connection->reconnect();
        $connection->onConnect = function ($con) {
            echo "重连成功\n";
        };
        $connection->onError = function ($con, $code, $msg) {
            echo "重连失败，错误码：$code 错误信息：$msg\n";
        };
    }

    public function onWorkerStart($worker)
    {
        //过期关闭连接
        Timer::add(1, function () use ($worker) {
            $time_now = time();
            foreach ($worker->connections as $connection) {
                if (empty($connection->lastMessageTime)) {
                    $connection->lastMessageTime = $time_now;
                }
                if ($time_now - $connection->lastMessageTime > self::$heartbeat_time) {      //连接超时
                    $connection->close();
                }
            }
//            file_get_contents("https://gas.zhixingjiuzhou.com/task/gas_station?time=" . microtime(true));
//            file_get_contents("https://gas.zhixingjiuzhou.com/task/open_station?time=" . microtime(true));
//            file_get_contents("https://gas.zhixingjiuzhou.com/task/settingDefaultPrice?time=" . microtime(true));
//            echo "执行定时任务\n";
        });

//        // 开启一个内部端口，方便内部系统推送数据，Text协议格式 文本+换行符
//        $inner_text_worker = new \Workerman\Worker('text://127.0.0.1:7866');
//
//        $inner_text_worker->onMessage = function ($connection, $buffer) {
//            // $data数组格式，里面有uid，表示向那个uid的页面推送数据
//            $data = json_decode($buffer, true);
//            $uid = $data['data']['store_mark'] ?? "";
//            $ret = true;
//            if (!empty($uid)) {
//                // 通过workerman，向uid的页面推送数据
//                $ret = $this->sendMessageByUid($uid, $buffer);
//            }
//
//            // 返回推送结果
//            $connection->send($ret ? 'ok' : 'fail');
//        };
        // ## 执行监听 ##
//        $inner_text_worker->listen();
    }

}
